<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
export default {
  name: 'SimEcharts',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    },
    autoResize: {
      type: Boolean,
      default: true
    },
    chartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        this.setOptions(val)
      }
    }
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.setOptions(this.chartData)
    },
    setOptions({ color, title, tooltip, legend, grid, toolbox, xAxis, yAxis, radar, series } = {}) {
      // ---------- 配置数据 -----开始-----
      // 存在color 则设置
      if (!(color && color.length)) color = ['#409EFF', '#1CA261', '#FFCD43', '#FF2525', '#2DC4D2', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
      let option = {
        color: color,
        title: title,
        tooltip: tooltip,
        legend: legend,
        grid: grid,
        toolbox: toolbox,
        xAxis: xAxis,
        yAxis: yAxis,
        radar: radar,
        series: series
      }
      // ---------- 配置数据 -----结束-----
      this.chart.setOption(option) // 设置图表
      const imgUrl = this.chart.getDataURL('png') // echarts生成图片
      this.$emit('image', imgUrl) //
    }
  }
}
</script>

<style lang="scss" scoped>
  .chart {
    //border: 1px solid #909399;
    //box-shadow: 0px 3px 6px #909399, 2px -3px 6px #909399;
    margin-bottom: 10px;
  }
</style>
